<template>
  <div class="ip-supplier">
    <div v-for="(item, index) in supplierAry" :key="index">
      <el-form
        :ref="'supplierAryForm' + index"
        :inline="true"
        :model="item"
        :rules="rule"
        label-width="70px"
        label-position="left"
      >
        <el-form-item label="供应商" prop="supplier">
          <selectWithUserLoad
            ref="selectUser"
            v-model="item.supplierObj"
            :hide-select-list="item.supplierObj && JSON.stringify(item.supplierObj) !== '{}' ?[item.supplierObj] : []"
            :select-data-list="item.supplierObj ?[item.supplierObj] : []"
            :multiple="false"
            :loadmore-method="getSuppliers()"
            style="width:240px;"
            placeholder="请选择供应商"
            extend-class="create-ip-order-select"
            value-type="object"
            key-name="id"
            label-name="supplier"
            filterable
            collapse-tags
            @change="supplierChange(item, item.supplierObj)"
          />
        </el-form-item>
        <el-form-item>
          <span
            v-if="item.supplierType || item.supplierType === 0"
          >{{ item.supplierType | supplierStatus }}</span>
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="item.way"
            size="small"
            clearable
            class="width110"
            style="width: 110px"
          >
            <el-option
              v-for="item in wayOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="item.way === 0">
          <el-input
            v-model="item.costRate"
            oninput="if(value>1)value=1;if(value<0)value=0;"
            name="costRate"
            type="number"
            placeholder="请输入分成比例0～1区间"
            size="small"
            @input="numberInputChange(item, 'costRate')"
            @mousewheel.native.prevent
          />
        </el-form-item>
        <el-form-item v-if="item.way === 1">
          <el-input
            v-model="item.costAmount"
            oninput="if(value>999999999)value=999999999;if(value<0)value=0;"
            name="costAmount"
            type="number"
            placeholder="请输入分成金额"
            size="small"
            @mousewheel.native.prevent
            @input="numberInputChange(item, 'costAmount')"
          />
        </el-form-item>
        <el-form-item>
          <div class="btn-box">
            <div class="delete-btn" @click="deleteCost(index)">
              <img :src="delIcon" alt="del" >
            </div>
            <!-- <div v-if="index === (supplierAry.length - 1)" class="add-btn" @click="addCost()">
              <img :src="plus" alt="del" >
            </div> -->
          </div>
        </el-form-item>
      </el-form>
    </div>
    <div>
      <el-button type="primary" class="add-cost" size="small" plain @click="addCost()">添加成本</el-button>
    </div>
  </div>
</template>
<script>
import { getMengliSuppliers } from '@/api/mengliOrder';
import selectWithUserLoad from '@/components/Common/selectWithUserLoad';
import delIcon from '@/assets/del-icon.png';
import plus from '@/assets/orderlist/plus.png';
import ElMessage from '@/utils/message';
export default {
  components: { selectWithUserLoad },
  filters: {
    supplierStatus(type) {
      const obj = {
        '0': '公司',
        '1': '个人'
      };
      return obj[String(type)] || '--';
    }
  },
  data() {
    return {
      delIcon,
      plus,
      supplierAry: [],
      rule: {
        supplier: [{ required: true, trigger: 'change', message: '请选择供应商' }]
      },
      wayOptions: [
        { value: 0, label: '分成比例' },
        { value: 1, label: '成本金额' }
      ]
    };
  },
  created() {
    this.getSuppliers();
  },
  methods: {
    changeInput(value) {
      let str = value.replace(/[^\d.]/g, ''); // 只允许数字
      // str = value.replace(/^[0]/g, ''); // 不允许零
      str = str.replace(/\.{2,}/g, '.'); // 连续两个小数点 replace为.
      str = str.replace(/^\./g, '0.'); // 已点为开头 replace为 0.
      str = str.replace(/^(\d*)\.(\d*)\./g, '$1.$2');// 不连续点点 删掉
      str = str.replace(/^0[^\.]+/g, '0'); // 连续多个0 replace为1个0
      str = str.replace(/^(\d+)\.(\d\d).*$/, '$1.$2'); // 只允许保留小数点后2位
      return str;
    },
    initInfo(supplierDefault) {
      const supplierAry = JSON.parse(JSON.stringify(supplierDefault || []));
      // 初始化数据
      if (supplierAry && supplierAry.length > 0) {
        supplierAry.forEach(item => {
          item.costAmount = (item.costAmount || item.costAmount === 0) ? item.costAmount / 100 : null;
          item.supplierObj = {
            id: item.supplierId, supplier: item.supplier
          };
        });
        this.supplierAry = supplierAry;
      }
    },
    getSuppliers() {
      const a = function(params) {
        return new Promise((resolve, reject) => {
          params.keyword = '';
          if (params.userName) params.keyword = params.userName;
          getMengliSuppliers(params)
            .then(res => {
              resolve(res);
            })
            .catch(err => {
              reject(err);
            });
        });
      };
      return a;
    },
    validateForm() {
      const params = [];
      this.supplierAry.forEach((item, index) => {
        params.push(...this.$refs['supplierAryForm' + index]);
      });
      return new Promise((resolve, reject) => {
        Promise.all(params.map(this.getFormPromise)).then(res => {
          const validateResult = res.every(item => !!item);
          if (validateResult) {
            resolve(true);
          } else {
            reject(false);
          }
        });
      });
    },
    getFormPromise(form) {
      return new Promise(resolve => {
        form.validate(res => {
          resolve(res);
        });
      });
    },
    supplierChange(item, supplierObj) {
      item.supplierType = supplierObj.supplierType;
      item.supplier = supplierObj.supplier;
      item.supplierId = supplierObj.id;
    },
    numberInputChange(item, key) {
      if (item[key]) item[key] = this.changeInput(item[key]);
    },
    deleteCost(index) {
      this.supplierAry.splice(index, 1);
    },
    addCost() {
      const obj = {
        supplier: '',
        supplierId: null,
        costRate: null,
        costAmount: null,
        supplierObj: {},
        way: null,
        supplierType: null
      };

      this.supplierAry.push(obj);
    },
    getParams() {
      const supplierAry = JSON.parse(JSON.stringify(this.supplierAry));
      const supplierIds = [];
      for (let i = 0; i < supplierAry.length; i++) {
        const item = supplierAry[i];
        item.costAmount = item.costAmount ? Math.round(Number(item.costAmount) * 100) : null;
        if (!item.supplierId || item.supplierId === '') {
          // ElMessage.error('请选择供应商');
          ElMessage.error('请填写完整的成本信息');
          return 'error';
        }
        if (item.way === null) {
          // ElMessage.error('请选择分成比例或成本金额');
          ElMessage.error('请填写完整的成本信息');
          return 'error';
        }
        if (item.way === 0 && !item.costRate && item.costRate !== 0) {
          // ElMessage.error('请填写分成比例');
          ElMessage.error('请填写完整的成本信息');
          return 'error';
        }
        if (item.way === 1 && !item.costAmount && item.costAmount !== 0) {
          // ElMessage.error('请填写分成金额');
          ElMessage.error('请填写完整的成本信息');
          return 'error';
        }
        if (!supplierIds.includes(item.supplierId)) {
          supplierIds.push(item.supplierId);
        } else {
          ElMessage.error('不可选择同一个供应商');
          return 'error';
        }
      }

      return supplierAry;
    }
  }
};
</script>
<style lang="scss" scoped>
.ip-supplier {
  margin-top: 20px;
  .btn-box {
    display: flex;
    align-items: center;
  }
  .add-btn {
    width: 32px;
    height: 32px;
    background: #eff3fb;
    border-radius: 4px;
    color: #406eff;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-left: 10px;
    cursor: pointer;
    img {
      width: 16px;
    }
  }
  .delete-btn {
    width: 32px;
    height: 32px;
    margin-left: 10px;
    cursor: pointer;
    img {
      width: 100%;
    }
  }
}
.add-cost {
  background: #fff;
}
.width110 {
  width: 110px;
  &::v-deep {
    .el-input {
      width: 110px !important;
      .el-input__inner {
        width: 110px;
      }
    }
  }
}
</style>
